//
//  HNSH_GoodsSpecView.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/25.
//

static CGFloat viewHeight = 412;

#import "HNSH_GoodsSpecView.h"

//view
#import "HNSH_GoodsSpecHeader.h"
#import "HNSH_GoodsSpecTitleHeader.h"
#import "HNSH_GoodsSpecCountFooter.h"
#import "HNSH_GoodsSpecItemCell.h"

@interface HNSH_GoodsSpecView ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UIGestureRecognizerDelegate>
/** */
@property (nonatomic, strong)UIView * bgView;
/** */
@property (nonatomic, strong)UIButton * cancelBtn;
/** */
@property (nonatomic, strong)UICollectionView * collectionView;
/** 加入购物车 */
@property (nonatomic, strong)UIButton * addCartButton;
/** 立即购买 */
@property (nonatomic, strong)UIButton * buyButton;
/**  */
@property (nonatomic, copy)HNSH_GoodsSpecBlock chooseSpeBlock;
/**  */
@property (nonatomic, strong)HNSH_GoodsSpecModel * specModel;
@property (nonatomic, strong)HNSH_GoodsSpecCountFooter * footerView;

/* goodsDetail */
@property (nonatomic, strong) HNSH_GoodsDetailModel *goodsDetail;
@end

static NSString *HNSH_GoodsSpecHeaderID = @"HNSH_GoodsSpecHeaderID";
static NSString *HNSH_GoodsSpecTitleHeaderID = @"HNSH_GoodsSpecTitleHeaderID";
static NSString *HNSH_GoodsSpecCountFooterID = @"HNSH_GoodsSpecCountFooterID";
static NSString *HNSH_GoodsSpecItemCellID = @"HNSH_GoodsSpecItemCellID";

@implementation HNSH_GoodsSpecView

+ (instancetype)showSpecificationViewWithSpecModel:(HNSH_GoodsSpecModel *)specModel goodsDetail:(HNSH_GoodsDetailModel *)goodsDetail block:(HNSH_GoodsSpecBlock)block {
    UIView * superView = [UIApplication sharedApplication].keyWindow;
    HNSH_GoodsSpecView * view = [[HNSH_GoodsSpecView alloc] initWithFrame:superView.bounds];
    view.goodsDetail = goodsDetail;
    view.chooseSpeBlock = block;
    view.specModel = specModel;
    [superView addSubview:view];
    [view showSpecificationView];
    return view;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addAllViews];
        [self addAllLayout];
    }
    return self;
}

//MARK: Cycle Methods
- (void)addAllViews{
    [self setDefault];
    [self addSubview:self.bgView];
    [self.bgView addSubview:self.cancelBtn];
    [self.bgView addSubview:self.collectionView];
    [self.bgView addSubview:self.addCartButton];
    [self.bgView addSubview:self.buyButton];
    [self.bgView sendSubviewToBack:self.collectionView];
}

- (void)setDefault{
    self.backgroundColor = RGBA(0, 0, 0, 0.4);
//    UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenSpecificationView)];
//    ges.delegate = self;
//    [self addGestureRecognizer:ges];
}

- (void)addAllLayout{
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
        make.top.mas_equalTo(self.bgView);
    }];
    CGFloat w = (kScreenWidth - 60) / 2;
    [self.addCartButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.width.mas_equalTo(w);
        make.height.mas_equalTo(36);
        make.bottom.mas_equalTo(-(kBottomSafeHeight + 9));
    }];
    [self.buyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.width.mas_equalTo(w);
        make.height.bottom.mas_equalTo(self.addCartButton);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.addCartButton.mas_top).offset(-9);
    }];
}


- (void)addCartButtonAction{
    HNSH_GoodsSpecListItem * model = [self getSpecModel];
    if (!model) {
        [kSTWindow makeToast:@"请选择商品规格"];
        return;
    }
    NSInteger count = self.footerView.count;
    if (self.chooseSpeBlock) {
        self.chooseSpeBlock(0, count<=0 ? 1 : count, model);
    }
    [self hiddenSpecificationView];
}

- (void)buyBtnAction {
    HNSH_GoodsSpecListItem * model = [self getSpecModel];
    if (!model) {
        [kSTWindow makeToast:@"请选择商品规格"];
        return;
    }
//    if ([self.specModel.goods_type integerValue] == 1) {
//        if ([model.integral doubleValue] <= 0) {
//            [kSTWindow makeToast:@"该商品只能使用现金购买"];
//            return;
//        }
//        if ([[ST_UserManager shareInstance].user.integral doubleValue] < [model.integral doubleValue]) {
//            [kSTWindow makeToast:@"种子不足"];
//            return;
//        }
//    } else if ([self.specModel.goods_type integerValue] == 2) {
//        if ([model.exchange_value doubleValue] <= 0) {
//            [kSTWindow makeToast:@"该商品只能使用现金购买"];
//            return;
//        }
//        if ([[ST_UserManager shareInstance].user.exchange_value doubleValue] < [model.exchange_value doubleValue]) {
//            [kSTWindow makeToast:@"购物值不足"];
//            return;
//        }
//    }
    
    NSInteger count = self.footerView.count;
    if (self.chooseSpeBlock) {
        self.chooseSpeBlock(1, count<=0 ? 1 : count, model);
    }
    [self hiddenSpecificationView];
}

- (HNSH_GoodsSpecListItem *)getSpecModel{
    return [self.specModel getCurrentItemModel];
}

//MARK: Setter Methods
- (void)setSpecModel:(HNSH_GoodsSpecModel *)specModel{
    _specModel = specModel;
    
    [self changeWidth];
    [self.collectionView reloadData];
}

- (void)changeWidth{
    NSArray * array = self.specModel.attribute_list;
    for (HNSH_GoodsSpecAttributeListItem * model in array) {
        for (int i = 0; i < model.items.count; i++) {
            HNSH_GoodsSpecAttributeItem * subModel = model.items[i];
            CGSize size = [subModel.item boundingRectWithSize:CGSizeMake(0, 28) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil].size;
            subModel.width = size.width < 76 ? 76 : (size.width + 10);
            if (i == 0) {
                subModel.isSelected = YES;
            }
        }
    }
}


//MARK: Myself Methods
- (void)showSpecificationView{
    [UIView animateWithDuration:0.5 animations:^{
        self.bgView.frame = CGRectMake(0, kScreenHeight - viewHeight - kBottomSafeHeight, kScreenWidth, viewHeight + kBottomSafeHeight);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hiddenSpecificationView{
    [UIView animateWithDuration:0.5 animations:^{
        self.bgView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, viewHeight + kBottomSafeHeight);
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}

//MARK: Getter Methods
- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [UIView new];
        _bgView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, viewHeight + kBottomSafeHeight);
        _bgView.backgroundColor = [UIColor appWhiteLabelColor];
        _bgView.layer.cornerRadius = 8;
        _bgView.layer.masksToBounds = YES;
    }
    return _bgView;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton new];
        [_cancelBtn setImage:[UIImage imageNamed:@"base_icon_close"] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(hiddenSpecificationView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[UICollectionViewFlowLayout new]];
        _collectionView.backgroundColor = [UIColor appWhiteLabelColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.userInteractionEnabled = YES;
        
        [_collectionView registerClass:[HNSH_GoodsSpecHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HNSH_GoodsSpecHeaderID];
        [_collectionView registerClass:[HNSH_GoodsSpecTitleHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HNSH_GoodsSpecTitleHeaderID];
        [_collectionView registerClass:[HNSH_GoodsSpecCountFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:HNSH_GoodsSpecCountFooterID];
        [_collectionView registerClass:[HNSH_GoodsSpecItemCell class] forCellWithReuseIdentifier:HNSH_GoodsSpecItemCellID];
    }
    return _collectionView;
}

- (UIButton *)addCartButton{
    if (!_addCartButton) {
        _addCartButton = [UIButton new];
        [_addCartButton setTitle:@"加入购物车" forState:UIControlStateNormal];
        [_addCartButton setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _addCartButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _addCartButton.layer.cornerRadius = 8;
        _addCartButton.layer.masksToBounds = YES;
        _addCartButton.backgroundColor = [UIColor colorWithHexString:@"#FFB900"];
        [_addCartButton addTarget:self action:@selector(addCartButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addCartButton;
}

- (UIButton *)buyButton{
    if (!_buyButton) {
        _buyButton = [UIButton new];
        [_buyButton setTitle:@"立即购买" forState:UIControlStateNormal];
        [_buyButton setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _buyButton.layer.cornerRadius = 8;
        _buyButton.layer.masksToBounds = YES;
        _buyButton.backgroundColor = [UIColor appGreenColor];
        [_buyButton addTarget:self action:@selector(buyBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buyButton;
}

//MARK: UICollectionViewDelegate Methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.specModel.attribute_list.count + 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    NSArray * array = self.specModel.attribute_list;
    HNSH_GoodsSpecAttributeListItem * model = array[section - 1];
    NSArray * subArray = model.items;
    return subArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return nil;
    }
    HNSH_GoodsSpecItemCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:HNSH_GoodsSpecItemCellID forIndexPath:indexPath];
    NSArray * array = self.specModel.attribute_list;
    HNSH_GoodsSpecAttributeListItem * model = array[indexPath.section - 1];
    NSArray * subArray = model.items;
    HNSH_GoodsSpecAttributeItem * subModel = subArray[indexPath.row];
    cell.title = subModel.item;
    cell.isSelected = subModel.isSelected;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeZero;
    }
    NSArray * array = self.specModel.attribute_list;
    HNSH_GoodsSpecAttributeListItem * model = array[indexPath.section - 1];
    NSArray * subArray = model.items;
    HNSH_GoodsSpecAttributeItem * subModel = subArray[indexPath.row];
    return CGSizeMake(subModel.width, 28);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 16, 0, 16);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 16;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 16;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 0) {
            HNSH_GoodsSpecHeader * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HNSH_GoodsSpecHeaderID forIndexPath:indexPath];
            view.goodsDetail = self.goodsDetail;
            view.specModel = self.specModel;
            return view;
        } else {
            HNSH_GoodsSpecTitleHeader * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HNSH_GoodsSpecTitleHeaderID forIndexPath:indexPath];
            NSArray * array = self.specModel.attribute_list;
            HNSH_GoodsSpecAttributeListItem * model = array[indexPath.section - 1];
            view.title = model.name;
            return view;
        }
    }
    if (kind == UICollectionElementKindSectionFooter) {
        if (indexPath.section == self.specModel.attribute_list.count) {
            HNSH_GoodsSpecCountFooter * view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HNSH_GoodsSpecCountFooterID forIndexPath:indexPath];
            HNSH_GoodsSpecListItem * model = [self getSpecModel];
            NSInteger count = [model.store_count integerValue];
            view.maxCount = count;
            self.footerView = view;
            return view;
        }
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(kScreenWidth, 124);
    }
    return CGSizeMake(kScreenWidth, 55);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == self.specModel.attribute_list.count) {
        return CGSizeMake(kScreenWidth, 44);
    }
    return CGSizeZero;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray * array = self.specModel.attribute_list;
    HNSH_GoodsSpecAttributeListItem * model = array[indexPath.section - 1];
    NSArray * subArray = model.items;
    HNSH_GoodsSpecAttributeItem * subModel = subArray[indexPath.row];
    [self changeStatusWithModel:model];
    subModel.isSelected = YES;
    [self.collectionView reloadData];
}

//MARK: 同一个规格下只能选择一个样式
- (void)changeStatusWithModel:(HNSH_GoodsSpecAttributeListItem *)model{
    NSArray * array = self.specModel.attribute_list;
    for (HNSH_GoodsSpecAttributeListItem * attM in array) {
        if ([attM.uid isEqualToString:model.uid]) {
            for (HNSH_GoodsSpecAttributeItem * subM in attM.items) {
                subM.isSelected = NO;
            }
        }
    }
}

@end
